const db = require("../db/index.js");
// 引入brycpt 加密中间件
const bcrypt = require("bcryptjs");
// 导入crypto模块 生成uuid
const crypto = require("crypto");
// 导入fs处理文件
const fs = require("fs");

/**
 * 上传头像
 */
exports.uploadAvatar = (req, res) => {
  const onlyId = crypto.randomUUID();
  let oldName = req.files[0].filename;
  let newName = Buffer.from(req.files[0].originalname, "latin1").toString(
    "utf-8"
  );
  // upload后面别忘记加/
  fs.renameSync("./public/upload/" + oldName, "./public/upload/" + newName);

  const sql = "insert into image set ?";
  db.query(
    sql,
    {
      image_url: `http://127.0.0.1:3007/upload/${newName}`,
      onlyId,
    },
    (err, results) => {
      if (err) return res.cc(err);
      res.send({
        onlyId: onlyId,
        status: 0,
        image_url: `http://127.0.0.1:3007/upload/${newName}`,
      });
    }
  );
};

/**
 * 绑定账号接口
 * 参数 body:account,onlyId,url
 */
exports.bindAccount = (req, res) => {
  const { account, onlyId, url } = req.body;

  const sql = "update image set account = ? where onlyId = ?";
  // 更新image表的account字段
  db.query(sql, [account, onlyId], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("绑定失败");
    const sql1 = "update users set image_url = ? where account = ?";
    // 更新users表的image_url字段
    db.query(sql1, [url, account], (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("绑定失败");
      res.send({
        status: 0,
        message: "绑定成功",
      });
    });
  });
};

/**
 * 更改用户密码
 * 参数 body:id,oldPassword,newPassword
 */
exports.changePassword = (req, res) => {
  let { id, oldPassword, newPassword } = req.body;
  const sql = "select password from users where id= ?";
  db.query(sql, id, (err, result) => {
    if (err) {
      return res.cc(err);
    }
    // 比较输入的密码与数据的密码是否相同
    const compareResult = bcrypt.compareSync(oldPassword, result[0].password);
    if (!compareResult && oldPassword !== result[0].password) {
      return res.cc("密码错误");
    }

    newPassword = bcrypt.hashSync(newPassword, 10);
    const sql1 = "update users set password = ? where id = ?";
    db.query(sql1, [newPassword, id], (err, result) => {
      if (err) return res.cc(err);
      res.send({
        status: 0,
        message: "修改成功",
      });
    });
  });
};
/**
 * 获取用户信息
 */
exports.getUserInfo = (req, res) => {
  const sql = "select * from  users where id = ?";
  db.query(sql, req.body.id, (err, results) => {
    if (err) return res.cc(err);
    results[0].password = "";
    res.send({
      status: 0,
      result: results[0],
      message: "查找信息成功",
    });
  });
};

/**
 * 修改用户姓名
 * 参数 body:id name
 */
exports.changeName = (req, res) => {
  const { id, name } = req.body;
  const sql = "update users set name = ? where id = ?";
  db.query(sql, [name, id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "名称更改成功",
    });
  });
};

/**
 * 修改用户性别
 * 参数 body:id,sex
 */
exports.changeSex = (req, res) => {
  const { id, sex } = req.body;
  const sql = "update users set sex = ? where id = ?";
  db.query(sql, [sex, id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "性别更改成功",
    });
  });
};

/**
 * 修改用户邮箱
 * 参数 body:id,email
 */
exports.changeEmail = (req, res) => {
  const { id, email } = req.body;
  const sql = "update users set email = ? where id = ?";
  db.query(sql, [email, id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "邮箱更改成功",
    });
  });
};

/**
 * 验证账户与邮箱是否一致
 * 参数 body:account,email
 */
exports.verifyAccountAndEmail = (req, res) => {
  const { account, email } = req.body;
  // 判断该账号是否存在
  const sql1 = "select * from users where account = ?";
  db.query(sql1, account, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("账户不存在");
    if (results[0].email !== email) return res.cc("邮箱与账户不匹配");
    res.send({
      status: 0,
      message: "验证成功",
      id: results[0].id,
    });
  });
};

/**
 * 登录页面修改密码
 * @body {id,newpassword}
 */
exports.changePasswordInLogin = (req, res) => {
  let { id, newPassword } = req.body;
  newPassword = bcrypt.hashSync(newPassword, 10);
  const sql = "update users set password = ? where id=?";
  db.query(sql, [newPassword, id], (err, results) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "修改成功",
    });
  });
};

// --------------------------用户管理-------------------------

/**
 * 添加管理员
 * @data account, password, name, sex, department, email, identity
 */
exports.createAdmin = (req, res) => {
  let { account, password, name, sex, department, email, identity } = req.body;
  const sql = "select * from users where account = ?";
  db.query(sql, account, (err, results) => {
    if (results.length > 0) {
      return res.cc("该账号已存在");
    }
    password = bcrypt.hashSync(password, 10);
    const sql1 = "insert users set ?";
    // 创建时间
    const create_time = new Date();
    db.query(
      sql1,
      {
        account,
        password,
        name,
        sex,
        department,
        email,
        identity,
        create_time,
      },
      (err, results) => {
        if (err) return res.cc(err);
        if (results.affectedRows !== 1) return res.cc("添加管理员失败");
        res.cc("添加管理员成功", 0);
      }
    );
  });
};

// 获取管理员列表
exports.getAdminList = (req, res) => {
  const sql = `select * from users where identity = ?`;
  db.query(sql, req.body.identity, (err, results) => {
    if (err) return res.cc(err);
    const { password, ...result } = results[0];
    res.send(result);
  });
};

/**编辑管理员账号信息
 * @data id, name, sex, email, department
 */
exports.editAdmin = (req, res) => {
  const { id, name, sex, email, department } = req.body;
  const date = new Date();
  const sql0 = "select department from users where id = ?";
  db.query(sql0, id, (err, result) => {
    if (result[0].department == department) {
      // 修改的内容
      const updateContent = {
        id,
        name,
        sex,
        email,
        department,
        update_time: date,
      };
      const sql = "update users set ? where id = ?";
      db.query(sql, [updateContent, updateContent.id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
          status: 0,
          message: "修改管理员信息成功",
        });
      });
    } else {
      // 修改的内容
      const updateContent = {
        id,
        name,
        sex,
        email,
        department,
        update_time: date,
        read_list: null,
        read_status: 0,
      };
      const sql = "update users set ? where id = ?";
      db.query(sql, [updateContent, updateContent.id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
          status: 0,
          message: "修改管理员信息成功",
        });
      });
    }
  });
};

/**
 * 对用户进行赋权
 * @data id identity
 */
exports.changeIdentityToAdmin = (req, res) => {
  const date = new Date();
  const sql = "update users set identity = ?,update_time = ? where id = ?";
  db.query(sql, [req.body.identity, date, req.body.id], (err, result) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "赋权成功",
    });
  });
};

/**
 * 通过账号对用户搜索
 * @data account
 */
exports.searchUser = (req, res) => {
  const { account } = req.body;
  const sql = "select * from users where account = ?";
  db.query(sql, account, (err, result) => {
    if (err) return res.cc(err);
    result.forEach((e) => {
      e.password = "";
      e.create_time = "";
      e.image_url = "";
      e.status = "";
    });
    res.send(result);
  });
};

/**
 * 冻结用户 通过id 把status 置为 1
 * @data id
 */
exports.banUser = (req, res) => {
  const status = 1;
  const sql = "update users set status = ? where id = ?";
  db.query(sql, [status, req.body.id], (err, result) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "冻结成功",
    });
  });
};

/**
 * 解冻用户 通过id 把status 置为 0
 * @data id
 */
exports.hotUser = (req, res) => {
  const status = 0;
  const sql = "update users set status = ? where id = ?";
  db.query(sql, [status, req.body.id], (err, result) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "解冻成功",
    });
  });
};

/**
 * 删除用户
 * @data id
 */
exports.deleteUser = (req, res) => {
  const sql = "delete from users where id = ?";
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err);
    res.send({
      status: 0,
      message: "删除成功",
    });
  });
};
